# !/usr/bin/env python3
# coding=utf-8

import time, sys, getopt, os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select

_gs105e_rate_limit = {
    "unlimit": 1,
    "limit": 3
}
gs105e_conf = {
    "url": "https://console.cloud.google.com/",
    "password": "0123456789",
    "rate": _gs105e_rate_limit["limit"],
    "port": "port2"
}


def browser(driver):
    print("打开交换机网页")
    driver.get(gs105e_conf["url"])

    print("输入密码")
    passwd_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "password")))
    passwd_input.send_keys(gs105e_conf["password"])

    print("点击登录")
    btn_login = driver.find_element_by_id("loginBtn")
    bt_login.click()

    print("点击 <QoS> 菜单")
    menu_qos = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "QoS")))
    menu_qos.click()

    print("点击 <Qos 速率限制> 菜单")
    menu_qos_ratelimit = driver.find_element_by_id("QoS_RateLimit")
    menu_qos_ratelimit.click()

    print("等待子页面加载完成")
    time.sleep(4)

    print("跳转至子页面")
    iframe = driver.find_element_by_xpath("//iframe[@id='maincontent']")
    driver.switch_to.frame(iframe)

    print("点击端口对应的 <checkbox>")
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, gs105e_conf["port"]))).click()
    print("选择入站速率")
    btn_select = driver.find_element_by_name("IngressRate")
    Select(btn_select).select_by_index(gs105e_conf["rate"])
    print("选择出站速率")
    btn_select = driver.find_element_by_name("EgressRate")
    Select(btn_select).select_by_index(gs105e_conf["rate"])

    print("由子页面返回主页面")
    driver.switch_to.default_content()
    print("点击 <应用> 按钮")
    btn_apply = driver.find_element_by_id("btn_Apply")
    btn_apply.click()

    print("点击 <退出> 按钮")
    btn_logout = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "logout")))
    btn_logout.click()


def main():
    try:
        chromedriver_path = "C:/Program Files/Google/Chrome/Application/chrome.exe"
        driver = webdriver.Chrome(chromedriver_path)
        browser(driver)
    except:
        print("error in script!")
    finally:
        print("Close Brwoser!")


if __name__ == "__main__":
    main()
